﻿using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.ServiceModel;

namespace Revit同步插件.HttpServer
{
  [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
  class InternalWallCreate : IWallCreate
  {

    WallCreateHandle createFunc;

    public InternalWallCreate()
    {
      createFunc = new WallCreateHandle();
    }

    public bool Create(List<P3> points, bool structural)
    {

      List<Curve> curves = new List<Curve>();
      XYZ last = null;
      for (int i = 0; i < points.Count; i++)
      {
        var p = new XYZ(points[i].X, points[i].Y, points[i].Z);
        if (last == null)
        {
          last = p;

          continue;
        }
        if (MathComparisonUtils.IsAlmostZero(p.DistanceTo(last)))
        {
          last = null;
          continue;
        }
        curves.Add(Line.CreateBound(last, p));
        last = p;
      }

      List<WallCreateData> data = new List<WallCreateData>();
      foreach (var c in curves)
      {
        var d = new WallCreateData() { LocationCurve = c };
        data.Add(d);
      }
      createFunc.Raise(data);
      return true;
    }

    public Func<bool> CreateFunc;


  }
  public class WallCreateData
  {
    public Curve LocationCurve;
  }

  public class WallCreateHandle : IExternalEventHandler
  {
    public WallCreateHandle()
    {
      mhandle = ExternalEvent.Create(this);
    }

    public void Execute(UIApplication app)
    {
      Document doc = app.ActiveUIDocument.Document;
      ViewPlan viewplan = doc.ActiveView as ViewPlan;
      using (Transaction t = new Transaction(doc))
      {
        t.Start("create");

        foreach (var item in mCreates)
        {
          try
          {
            Wall.Create(doc, item.LocationCurve, viewplan.GenLevel.Id, false);

          }
          catch (Exception)
          {

          }
        }
        t.Commit();
      }
    }

    public void Raise(IEnumerable<WallCreateData> datas)
    {
      mCreates = datas;
      if (null != datas)
      {
        mhandle.Raise();
      }
    }

    public string GetName()
    {
      return "create墙";
    }

    ExternalEvent mhandle;
    IEnumerable<WallCreateData> mCreates;
  }


}
